<?php
require_once 'inc.php';

class Helpdesk_Email_Gateway 
{
	public $emailGaterway = null;
	
	/**
	 * Help in make sender email (from) more Human-readable
	 */
	private function _fromDecoder($from)
	{
		$from = htmlentities($from);
		$from = explode("&lt;",$from);
		$patterns = array("<", ">", "&gt;", "&lt;");
		return trim(str_replace($patterns, '', $from[1]));
	}
	
	/**
	 * Help in make subject email more Human-readable
	 */
	private function _subjectDecoder($subject){
		$subject = imap_mime_header_decode($subject);
		return $subject[0]->text;
	}
	
	/**
	 * Help in make recive email (to) more Human-readable
	 */
	private function _toDecoder($to){
		$to = htmlentities($to);
		$to = explode("&lt;",$to);
		$patterns = array("<", ">", "&gt;", "&lt;");
		if(sizeof($to)>1)
			return trim(str_replace($patterns, '', $to[1]));
		if(is_array($to))
			return $to[0];
		return $to;
	}
	
	/**
	 * Help in make sender name more Human-readable
	 */
	private function _nameDecoder($from){
		var_dump($from);
		
		$from = imap_mime_header_decode($from);
		
		echo '<br />';
		var_dump($from);
		die;
		
		$from = explode("&lt;",$from);
		$patterns = array("<", ">", "&gt;", "&lt;");
		
		
		return trim(str_replace($patterns, '', $from[0]));
	}

	function connectGateway()
	{	
		$request = 	array(
			'host' => 'mail.phetbook.com',
			'user' 	 => 'gateway@phetbook.com',
			'password' => '?r*<r@q3nX*F');
			
		$dataConnect = array('host' => $request['host'],
							 'user' => $request['user'],
							 'password' => $request['password'],
		);
		
		//$dataConnect['ssl'] = 'SSL'; // 'TLS'
		//$dataConnect['port'] = 993;
		
		try {
			$this->emailGaterway = new Zend_Mail_Storage_Imap($dataConnect);
		} catch (Exception $e) {
			echo 'The Gateway: ' . $dataConnect['host'] . ' is failed connect!';
		}
	}
	
	public function processRetriveMail()
	{
		$numsMessage = (int) $this->emailGaterway->countMessages();
		if ($numsMessage > 0) {
			echo $numsMessage . " messages found.";

			$keepAlive = 0;
			for ($n = $numsMessage; $n > 0; $n--) {
				$message = $this->emailGaterway->getMessage($n);
				$from = $this->_fromDecoder($message->from);
				$date = date("Y-m-d h:i:s", strtotime($message->date)); 
				$subject = $this->_subjectDecoder($message->subject);
				$to  = $this->_toDecoder($message->envelopeTo);
				$senderName  = $this->_nameDecoder($message->from);
			}				
		}
	}
}
?>
<!DOCTYPE html>
<html lang=en>
<head>
	<meta charset=UTF-8>
</head>
<body>
 
<?php
$emailGaterway = new Helpdesk_Email_Gateway();
$emailGaterway->connectGateway();
$emailGaterway->processRetriveMail();
?>
</body>
</html>

	
		


	
						 
						 